#coding=utf-8
import uliweb.form as form
from uliweb.utils.generic import ReferenceSelectField
from uliweb.form import BaseField

class TestForm(form.Form):
    def form_validate(self, data):
        from uliweb.orm import get_model
        from sqlalchemy.sql import and_, or_, not_
        
        error = {}
        
        Test = get_model('test')
#        objs = Tasks_Develop.filter(Tasks_Develop.c.task_sys == data['system'])
#        obj = None
        if Test.filter(and_(Test.c.system == int(data['system']),Test.c.function_code == data['function_code'])).count()>1:
            error['function_code'] = u'功能代码重复，请检查！'
#        for x in objs:
#            if x.version_date == data['version_date']:
#                obj = x
#                break
#        System = get_model('system')
#        sys = System.get(System.c.id==int(data['system']))
#        version = sys.abbr+'_'+str(data['version_date'])
#        sysname = sys.sys_id + '-' +sys.abbr+'('+sys.name+')'
#        if obj:
#            error={}
#        else:
#            error['version_date'] = '在系统中不存在测试版本为'+str(version)+'的可开发任务'
        return error


class TestImportForm(form.Form):
    system = ReferenceSelectField('system', label='所属系统', required=True)
    func_file = form.FileField('导入文件', required=True)
    
    def form_validate(self, data):
        error = {}
        
        return error
    
class VerificationTestImportForm(form.Form):
    func_file = form.FileField('导入文件', required=True)
    
    def form_validate(self, data):
        error = {}
        
        return error

class EnvField(BaseField):
    def html(self, data='', py=True):
        """
        Convert data to html value format.
        """
        from uliweb import settings
        from uliweb.core.html import Buf
        from uliweb.utils.common import get_choice
        
        data = data or []
        
        if self.static:
            txt = Buf()
#            with txt.fieldset(id=self.id):
#                with txt.legend:
#                    txt << '新环境需求'
            for row in data:
                v = str(row['category'])
                dv = get_choice(settings.PARA.TEST_ENV_CATEGORY, v)
                v1 = str(row.get('type', ''))
                v2 = str(row.get('amount', 0))
                v3 = str(row.get('unit', 0))
                if v == '1':
                    tpl = ('<li>'+dv
                        + ' 型号:'+get_choice(settings.PARA.TEST_ENV_MINICOMPUTER, v1)
                        + ' 台数:'+v2
                        + ' 单台CPU数:'+v3
                        + '</li>')
                elif v == '2':
                    tpl = ('<li>'+dv
                        + ' 台数:'+v2
                        + ' 单台CPU数:'+v3
                        + '</li>')
                elif v == '3':
                    tpl = ('<li>'+dv
                        + ' 型号:'+get_choice(settings.PARA.TEST_ENV_STORAGE, v1)
                        + ' 容量:'+v2
                        + '</li>')
                elif v == '4':
                    tpl = ('<li>'+dv
                        + ' 需求类型:'+get_choice(settings.PARA.TEST_ENV_NETWORK, v1)
                        + '</li>')
                txt << tpl
                
            return str(txt)
        else:
            txt = Buf()
            with txt.fieldset(id=self.id):
                with txt.legend:
                    txt << '新环境需求'
                with txt.div(_class="new_env_content"):
                    b = []
                    for number, row in enumerate(data):
                        v = str(row['category'])
                        dv = get_choice(settings.PARA.TEST_ENV_CATEGORY, v)
                        v1 = str(row.get('type', ''))
                        v2 = str(row.get('amount', 0))
                        v3 = str(row.get('unit', 0))
                        number = str(number)
                        if v == '1':
                            tpl = ('<li><span class="delete_env">&times;</span>'+dv
                                + ' 型号:'+get_choice(settings.PARA.TEST_ENV_MINICOMPUTER, v1)
                                + ' 台数:'+v2
                                + ' 单台CPU数:'+v3
                                + ' <input type="hidden" name="new_env_category_'+number+ '" value="' + v + '"></input>'
                                + ' <input type="hidden" name="new_env_type_'+number+ '" value="' + v1 + '"></input>'
                                + ' <input type="hidden" name="new_env_amount_'+number+ '" value="' + v2 + '"></input>'
                                + ' <input type="hidden" name="new_env_unit_'+number+ '" value="' + v3 + '"></input>'
                                + '</li>')
                        elif v == '2':
                            tpl = ('<li><span class="delete_env">&times;</span>'+dv
                                + ' 台数:'+v2
                                + ' 单台CPU数:'+v3
                                + ' <input type="hidden" name="new_env_category_'+number+ '" value="' + v + '"></input>'
                                + ' <input type="hidden" name="new_env_amount_'+number+ '" value="' + v2 + '"></input>'
                                + ' <input type="hidden" name="new_env_unit_'+number+ '" value="' + v3 + '"></input>'
                                + '</li>')
                        elif v == '3':
                            tpl = ('<li><span class="delete_env">&times;</span>'+dv
                                + ' 型号:'+get_choice(settings.PARA.TEST_ENV_STORAGE, v1)
                                + ' 容量:'+v2
                                + ' <input type="hidden" name="new_env_category_'+number+ '" value="' + v + '"></input>'
                                + ' <input type="hidden" name="new_env_type_'+number+ '" value="' + v1 + '"></input>'
                                + ' <input type="hidden" name="new_env_amount_'+number+ '" value="' + v2 + '"></input>'
                                + '</li>')
                        elif v == '4':
                            tpl = ('<li><span class="delete_env">&times;</span>'+dv
                                + ' 需求类型:'+get_choice(settings.PARA.TEST_ENV_NETWORK, v1)
                                + ' <input type="hidden" name="new_env_category_'+number+ '" value="' + v + '"></input>'
                                + ' <input type="hidden" name="new_env_type_'+number+ '" value="' + v1 + '"></input>'
                                + '</li>')
                        txt << tpl
                with txt.div(_class="bottom"):
                    with txt.label(_for='select_env_category'):
                        txt << '环境分类'
                    with txt.select(id="select_env_category"):
                        txt << '<option value=""></option>'
                        
                        for (k, v) in settings.PARA.TEST_ENV_CATEGORY:
                            txt << '<option value="%s">%s</option>' % (k, v)
                    with txt.a(_class="btn btn-green", id="btn_add_env"):
                        txt << '添加'
            return str(txt)

    def parse_data(self, request, all_data):
        if not isinstance(request, (tuple, list)):
            request = [request]
        result = []
        for r in request:
            for k, v in r.items():
                d = {}
                if k.startswith('new_env_category_'):
                    n = k.rsplit('_', 1)[1]
                    k1 = 'new_env_type_' + n
                    k2 = 'new_env_amount_' + n
                    k3 = 'new_env_unit_' + n
                    
                    d['category'] = v
                    if v == '1':
                        d['type'] = r.get(k1)
                        d['amount'] = int(r.get(k2))
                        d['unit'] = int(r.get(k3))
                    elif v == '2':
                        d['amount'] = int(r.get(k2))
                        d['unit'] = int(r.get(k3))
                    elif v == '3':
                        d['type'] = r.get(k1)
                        d['amount'] = int(r.get(k2))
                    elif v == '4':
                        d['type'] = r.get(k1)
                    result.append(d)
        all_data[self.name] = result
